<template>
    <div class="echarts" ref="echartsBar" :style="{ minHeight: '100px' }">
    </div>
</template>
<script>
import { onResizeChang, markLineF } from '../js/common';
let itemStyleColor = ['#19859E', '#29DDCF', '#0777C1']
export default {
    name: 'bar',
    props: {
        // 类型
        type: {
            type: String,
            default: () => ''
        },
        /** 包含
         *  markLine：{
         *  label:'',// 名称
         *  value:'',// 固定值
         * }
         * 
        */
        // 一些配置项
        setting: {
            type: Object,
            default: () => { }
        },
        // 数据
        data: {
            type: [Object, Array],
            default: () => [],
        },
    },
    data() {
        return {
            timesName: null,
        }
    },
    created() {
        // 监听屏幕改变的话就调用
        onResizeChang('start', this.onResizeChange)
    },
    methods: {
        echartInit() {
            var myChart = this.$echarts.init(this.$refs.echartsBar);
            let type = this.type;
            let company = this.setting.tooltip && this.setting.tooltip.company ? this.setting.tooltip.company : ['', ''];
            var option = {
                // 图例位置
                legend: {},
                tooltip: {
                    formatter: function (params) {
                        var color = params.color.colorStops[0].color;
                        var res = `<div "><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span> ${params.name}${company[0]}<span style="color:#16D5FF;margin-left:12px;padding-right:6px;">${params.value}${company[1]}</span></div>`;
                        return res;
                    }
                },
                // 图像大小
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '10%',
                    top: '5%',
                    containLabel: true,
                    ...this.setting.grid,
                },
                textStyle: {
                    color: "#ffffff"
                },
                xAxis: {
                    axisLabel: {
                        color: this.labelColor,//'#C5C0BF',
                        fontSize: this.setting.fontSize || 10,
                        formatter: (value) => {
                            if (this.setting && Object.keys(this.setting).length > 0 && this.setting.labelFormter) {
                                function chunkString(str, chunkSize) {
                                    let chunks = [];
                                    for (let i = 0; i < str.length; i += chunkSize) {
                                        chunks.push(str.substr(i, chunkSize));
                                    }
                                    return chunks;
                                }
                                let n = typeof (this.setting.labelFormter) == 'number' ? this.setting.labelFormter : 4
                                let res = chunkString(value, n);
                                res = res.join('\n')
                                return res;
                            } else {
                                return value;
                            }
                        },
                        ...this.setting.xAxisSetting,
                    },
                },
                yAxis: {
                    axisLabel: {
                        color: this.labelColor,//'#C5C0BF',
                        fontSize: this.setting.fontSize || 10,
                        ...this.setting.yAxisSetting,
                    },
                },
                series: [{
                    name: '',
                    type: 'bar',
                    // 图形颜色
                    itemStyle: {
                        // color: '#06F3F2',
                        barBorderRadius: [20, 20, 20, 20],
                        color: {
                            type: 'linear',
                            x: 0, //右
                            y: 0, //下
                            x2: 0, //左
                            y2: 1, //上
                            colorStops: [
                                {
                                    offset: 0,
                                    color: Array.isArray(this.setting.colorStops) && this.setting.colorStops[0] ? this.setting.colorStops[0] : '#16D5FF',
                                },
                                {
                                    offset: 1,
                                    color: Array.isArray(this.setting.colorStops) && this.setting.colorStops[this.setting.colorStops.length - 1] ? this.setting.colorStops[this.setting.colorStops.length - 1] : '#165DFF00',
                                }
                            ]
                        },
                    },
                    barMaxWidth: this.setting.barMaxWidth || 12,
                    data: [],
                }]
            };
            // 对齐线换为虚线
            let splitLine = {
                lineStyle: {
                    type: 'dashed',
                    color: '#cdcdcd'
                },
                show: true,
            }
            if (type == 'bar') {
                // 普通柱形图
                option['yAxis'] = {
                    ...option['yAxis'],
                    type: 'value',
                    splitLine: splitLine,
                }

                option['xAxis'] = {
                    ...option['xAxis'],
                    data: (this.getSplitData.label.length < 15 && !this.setting.isShow) ? this.getSplitData.label.concat(['', '', '', '',]) : this.getSplitData.label,
                }
                let dataList = this.getSplitData.value;
                option['series'][0]['data'] = dataList;
            }
            myChart.setOption(option);
        },
        // 重新计算
        onResizeChange() {
            var myChart = this.$echarts.init(this.$refs.echartsBar);
            myChart.resize();
        },
    },
    mounted() {
        // 解决页面不聚焦的时候柱形图丢失问题
        this.echartInit();
        this.$nextTick(() => {
            this.timesName = setInterval(() => {
                this.echartInit();
            }, 1000)
        })
        this.observer = new ResizeObserver((entries) => {
            this.onResizeChange();
        });
        this.observer.observe(this.$refs.echartsBar);
        window.addEventListener('resize', this.onResizeChange);
    },
    watch: {
        data(newVal, oldVal) {
            // 当 parentData 变化时，这个函数会被调用
            this.echartInit();
            this.onResizeChange();
        }
    },
    computed: {
        // data里面包含 label value
        getSplitData() {
            let arr = {
                label: [],
                value: [],
            };
            this.data.filter((val, index) => {
                arr['label'].push(val.label);
                arr['value'].push(val.value);
            })
            return arr
        },
        labelColor() {
            if (this.setting.label && this.setting.label.color) {
                return this.setting.label.color
            } else {
                return "#C5C0BF"
            }
        },
    },
    // 销毁
    beforeDestroy() {
        onResizeChang('end', this.onResizeChange)
        clearInterval(this.timesName);
        this.observer.disconnect();
        this.timesName = null;
    }
}
</script>
<style lang="less" scoped>
.echarts {
    width: 100%;
    height: 100%;
}
</style>